<?php

	class AuthController extends Zend_Controller_Action
	{
	
	    public function init()
	    {

	    }
	
	    public function indexAction()
	    {
	    	
		}
		
		public function loginAction()
		{
			try {
				$form = new Default_Form_Login('');
				$this->view->message = '';
				session_start();
				if (isset($_SESSION["page"]) == false){
					$_SESSION["page"] = $_SERVER['REQUEST_URI'];
				}else{
					$_SESSION["page"] = $_SERVER['REQUEST_URI'];
				}
				
				if($this->getRequest()->isPost()) {
					$auth = Zend_Auth::getInstance();
					$data = $this->_request->getPost();
					
					if ($form->isValid($data)) {
						$username = $this->getRequest()->getPost('username');
						$password = $this->getRequest()->getPost('password');
						
						$db = new Zend_Db_Adapter_Mysqli(array(
   							'host'     => 'mysql.spagooy.com',
						    'username' => 'web37108_hikuser',
						    'password' => '1!AssssQ',
						    'dbname'   => 'web37108_hik'
						));
						
						$adapter = new Zend_Auth_Adapter_DbTable($db,
							'spagooy_user',
							'spagooy_user_username',
							'spagooy_user_password',
							'md5(?) and spagooy_user_active = 1'
						);
												
						$adapter->setIdentity($username);
						$adapter->setCredential($password);
						
						$result = $auth->authenticate($adapter);

						if ($result->isValid())
						{							
							$auth->getStorage()->write($adapter->getResultRowObject(array('spagooy_user_id','spagooy_user_first_name','spagooy_user_last_name','spagooy_user_username','spagooy_user_role', 'spagooy_user_language', 'spagooy_user_sex', 'spagooy_user_email')));
							$page = $_SESSION["page"];
							
							if ($page == "/login")
							{
								$page = "/game";
							}
							else if (substr($page, 3) == "/login")
							{
								$page = substr($page,0,3) . "/game";
							}
							
							$_SESSION["page"] = null;				
							$_SESSION[yatzy][game] = null;
							$this->_helper->getHelper('Redirector')->gotoUrl($page);
						}
						else 
						{
							$this->view->message = Zend_Registry::get('translate')->_('INCORRECT_LOG_IN');

						}
					} else {
						$this->view->message = Zend_Registry::get('translate')->_('INCORRECT_LOG_IN');
					}	
				}
				$this->view->form = $form;
			} catch(Exception $e) {
				Zend_Registry::get('errLog')->err('Login error: ' . $e);
				$this->view->message = Zend_Registry::get('translate')->_('LOG_IN_ERROR');				
			}
		}
		
		public function logoutAction()
		{	
			$url = $_SERVER['REQUEST_URI'];
//Zend_Debug::dump($url);		
			if (substr($url,3) == "/logout")
			{
//Zend_Debug::dump("if");die();		
				Zend_Auth::getInstance()->clearIdentity();
				$this->_redirect(substr($url,0,3).'/login');
			}
			else
			{
//Zend_Debug::dump("else");die();		
				Zend_Auth::getInstance()->clearIdentity();
				$this->_redirect('/login');
			}
		}
	}